package com.jcrj.service;

import com.jcrj.dao.FlowFormDao;
import com.jcrj.entity.OFlowForm;
import com.jcrj.entity.OFlowFormProporty;
import com.jcrj.entity.OFormDefinition;
import com.jcrj.entity.OProcessinstance;
import com.jcrj.entity.OUser;
import com.jcrj.util.CreateForm;
import com.jcrj.util.DateUtil;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FlowFormService
{
  private FlowFormDao flowFormDao;

  public FlowFormDao getFlowFormDao()
  {
    return this.flowFormDao;
  }

  public void setFlowFormDao(FlowFormDao flowFormDao) {
    this.flowFormDao = flowFormDao;
  }

  public void saveFlowForm(OFlowForm flowForm) {
    this.flowFormDao.saveFlowForm(flowForm);
    String sql = "create table " + flowForm.getTableName() + " ( id int primary key,userId number(10),instanceId number(10),reject varchar2(10),reject_s varchar2(200),flowId varchar2(50),createTime varchar2(20))";
    this.flowFormDao.executeSql(sql);
  }

  public OFlowForm getFlowFormById(int id) {
    return (OFlowForm)this.flowFormDao.getObject(new OFlowForm(), id);
  }

  public void updateFlowForm(OFlowForm flowForm) {
    this.flowFormDao.updateFlowForm(flowForm);
  }

  public List<OFlowForm> flowFormList(String formName, int currentPage) {
    String hql = "from OFlowForm   ";
    if ((formName != null) && (!"".equals(formName))) {
      hql = hql + " where formName like '%" + formName.trim() + "%'";
    }
    hql = hql + " order by id desc";
    return this.flowFormDao.findByPage(hql, currentPage);
  }

  public Long contFlowForm(String formName) {
    String hql = " select count(id) from OFlowForm ";
    if ((formName != null) && (!"".equals(formName))) {
      hql = hql + " where formName like '%" + formName.trim() + "%'";
    }
    return this.flowFormDao.countTotalByHql(hql);
  }

  public void deleteFlowForm(String[] ids) {
    if (ids != null)
      for (int i = 0; i < ids.length; i++) {
        OFlowForm form = getFlowFormById(Integer.parseInt(ids[i]));
        String sql = "drop table " + form.getTableName();
        this.flowFormDao.executeSql(sql);
        this.flowFormDao.deleteFlowForm(form);
        String hql1 = "delete from OFlowFormProporty where formid=" + form.getId();
        this.flowFormDao.executeHql(hql1);
      }
  }

  public List<OFlowFormProporty> flowFormProportyList(int formId, String name) {
    String hql = "from OFlowFormProporty where formid=" + formId;
    if ((name != null) && (!"".equals(name))) {
      hql = hql + " and proportyName like '%" + name.trim() + "%'";
    }
    hql = hql + "order by id asc";
    return this.flowFormDao.findByHql(hql);
  }

  public List<OFlowFormProporty> flowFormProportyList(int formId) {
    OFormDefinition definition = getFormDefinition(formId);
    String hql = "from OFlowFormProporty where formid=" + definition.getFormId() + " order by id asc";
    return this.flowFormDao.findByHql(hql);
  }

  public String getFlowFormProportytoString(int formId) {
    String hql = "from OFlowFormProporty where formid=" + formId;
    List<OFlowFormProporty> list = this.flowFormDao.findByHql(hql);
    String proporty = "";
    for (OFlowFormProporty p : list) {
      if ("".equals(proporty))
        proporty = proporty + p.getColumnName();
      else {
        proporty = proporty + "," + p.getColumnName();
      }
    }

    return proporty;
  }

  public void saveFlowFormProporty(OFlowFormProporty formProporty, String tableName) {
    this.flowFormDao.saveFlowFormProporty(formProporty);
    String sql = "alter table " + tableName + " add " + formProporty.getColumnName() + " varchar2(" + formProporty.getProportyLen().intValue() * 2 + ")";
    this.flowFormDao.executeSql(sql);
  }

  public OFlowFormProporty getFlowFormProporty(int id) {
    return (OFlowFormProporty)this.flowFormDao.getObject(new OFlowFormProporty(), id);
  }

  public void updateFlowFormProporty(OFlowFormProporty formProporty) {
    this.flowFormDao.updateFlowFormProporty(formProporty);
  }

  public void deleteFlowFormProporty(String[] ids) {
    if ((ids != null) && (!"".equals(ids)))
      for (int i = 0; i < ids.length; i++) {
        OFlowFormProporty proporty = getFlowFormProporty(Integer.parseInt(ids[i]));
        OFlowForm form = getFlowFormById(proporty.getFormid().intValue());
        String sql = "alter table " + form.getTableName() + " drop column " + proporty.getColumnName();
        this.flowFormDao.executeSql(sql);
        this.flowFormDao.deleteFlowFormProporty(proporty);
      }
  }

  public List<OFormDefinition> formDefinitionList(String formName, int currentPage)
  {
    String hql = " from OFormDefinition o";
    if ((formName != null) && (!"".equals(formName))) {
      hql = hql + " where name like '%" + formName + "%'";
    }
    hql = hql + " order by o.createTime desc,o.id desc";
    return this.flowFormDao.findByPage(hql, currentPage);
  }

  public Long countFormDefinition(String formName) {
    String hql = "select count(id) from OFormDefinition";
    if ((formName != null) && (!"".equals(formName))) {
      hql = hql + " where name like '%" + formName + "%'";
    }
    return this.flowFormDao.countTotalByHql(hql);
  }
  public List<OFlowForm> flowFormList() {
    String hql = "from OFlowForm order by id desc";
    return this.flowFormDao.findByHql(hql);
  }

  public List<OFormDefinition> getFormDefinitionList() {
    String hql = "from OFormDefinition";
    return this.flowFormDao.findByHql(hql);
  }

  public void saveFormDefinition(OFormDefinition definition) {
    OFlowForm form = getFlowFormById(definition.getFormId().intValue());
    definition.setFormName(form.getFormName());
    this.flowFormDao.saveFormDefinition(definition);
  }

  public void updateFormDefinition(OFormDefinition definition) {
    OFlowForm form = getFlowFormById(definition.getFormId().intValue());
    definition.setFormName(form.getFormName());
    this.flowFormDao.updateFormDefinition(definition);
  }
  public OFormDefinition getFormDefinition(int id) {
    return (OFormDefinition)this.flowFormDao.getObject(new OFormDefinition(), id);
  }
  public void deleteFormDefinition(String[] ids) {
    if ((ids != null) && (ids.length > 0)) {
      String id = "";
      for (int i = 0; i < ids.length; i++) {
        if ("".equals(id))
          id = id + ids[i];
        else {
          id = id + "," + ids[i];
        }
      }
      String hql = "delete from OFormDefinition where id in(" + id + ")";
      this.flowFormDao.executeHql(hql);
    }
  }

  public String getFormStyle(int cols, int formId) {
    List list = flowFormProportyList(formId, null);
    StringBuffer buff = new StringBuffer();
    if ((list != null) && (!list.isEmpty())) {
      buff.append("<p align=\"center\"><strong><span style=\"font-family:宋体;color:black;font-size:16pt;mso-ascii-font-family:Arial;mso-hansi-font-family:Arial;mso-bidi-font-family:Arial;\">").append(((OFlowFormProporty)list.get(0)).getFormName()).append("</span></strong></p>");
      buff.append("<table style=\"width:100%;border-collapse:collapse;\" border='1' cellspacing='0' bordercolor='#000000'><tbody>");
      int count = 0;
      int len = 0;
      if (list.size() % cols != 0)
        len = list.size() / cols + 1;
      else {
        len = list.size() / cols;
      }
      for (int i = 0; i < len; i++) {
        buff.append("<tr style='border: 1px #000 solid;'>");
        for (int j = 0; j < cols; j++) {
          if (count < list.size()) {
            OFlowFormProporty proporty = (OFlowFormProporty)list.get(count);
            buff.append("<td style='border: 1px #000 solid;'>").append(proporty.getProportyName()).append("</td>");
            buff.append("<td style='border: 1px #000 solid;'>").append(CreateForm.getProportyToHtml(proporty.getColumnName(), proporty.getProportyLen().intValue(), proporty.getType(), proporty.getDefaultValue())).append("</td>");
            count++;
          } else {
            buff.append("<td style='border: 1px #000 solid;'>").append("&nbsp;").append("</td>");
            buff.append("<td style='border: 1px #000 solid;'>").append("&nbsp;").append("</td>");
          }
        }
        buff.append("</tr>");
      }
      buff.append("</tbody></table>");
    }
    return buff.toString();
  }

  public String getTableName()
  {
    String sql = "select TABLE_SEQ.nextval from dual";
    List list = this.flowFormDao.findBySql(sql);
    Object obj = list.get(0);
    String tableName = "jcoa$t" + obj;
    return tableName;
  }
  public String getColumnName() {
    String sql = "select TABLE_SEQ.nextval from dual";
    List list = this.flowFormDao.findBySql(sql);
    Object obj = list.get(0);
    String columnName = "jcoa_c" + obj;
    return columnName;
  }

  public String getTableKey() {
    String sql = "select FLOWFORM_SEQ.nextval from dual";
    List list = this.flowFormDao.findBySql(sql);
    String keys = ((BigDecimal)list.get(0)).toString();
    return keys;
  }

  public String saveFormContent(int formId, Map<String, String> map, int instanceId) {
    OFlowForm form = (OFlowForm)this.flowFormDao.getObject(new OFlowForm(), formId);
    String hql = "from OFlowFormProporty where formid=" + formId;
    List<OFlowFormProporty> list = this.flowFormDao.findByHql(hql);
    String keys = getTableKey();
    String sql = "insert into " + form.getTableName() + "(id,userId,instanceId,flowId,createTime";
    for (OFlowFormProporty p : list) {
      sql = sql + "," + p.getColumnName();
    }
    sql = sql + ") values (" + keys + "," + (String)map.get("userId") + "," + instanceId + "," + (String)map.get("flowId") + ",'" + DateUtil.DateToString(new Date()) + "'";
    for (OFlowFormProporty p : list) {
      sql = sql + ",'" + isEmpty(map.get(p.getColumnName())) + "'";
    }
    sql = sql + ")";
    this.flowFormDao.executeSql(sql);
    return keys;
  }

  public void updateFormContent(String id, int formId, Map<String, String> map) {
    OFlowForm form = (OFlowForm)this.flowFormDao.getObject(new OFlowForm(), formId);
    String hql = "from OFlowFormProporty where formid=" + formId;
    List<OFlowFormProporty> list = this.flowFormDao.findByHql(hql);
    String sql = "update " + form.getTableName() + " set id=" + id + ",instanceId=" + (String)map.get("instanceId") + ",reject='',reject_s=''";
    for (OFlowFormProporty p : list) {
      if ((map.get(p.getColumnName()) != null) && (!"".equals(map.get(p.getColumnName())))) {
        sql = sql + "," + p.getColumnName() + "='" + isEmpty(map.get(p.getColumnName())) + "' ";
      }
    }
    sql = sql + " where id=" + id;
    this.flowFormDao.executeSql(sql);
  }

  public List findFormList(int formId, List<OProcessinstance> instance, int flowId, int currentPage) {
    OFormDefinition definition = getFormDefinition(formId);
    OFlowForm form = getFlowFormById(definition.getFormId().intValue());
    List<OFlowFormProporty> list = flowFormProportyList(definition.getFormId().intValue(), null);
    String sql = "select id";
    for (OFlowFormProporty p : list) {
      sql = sql + " ," + p.getColumnName();
    }
    sql = sql + " from " + form.getTableName() + " where instanceId in (" + listToString(instance) + ") and flowId='" + flowId + "'";
    return this.flowFormDao.findByPageSql(sql, currentPage);
  }

  public Long countFormTotal(int formId, List<OProcessinstance> instance, int flowId)
  {
    OFormDefinition definition = getFormDefinition(formId);
    OFlowForm form = getFlowFormById(definition.getFormId().intValue());
    String sql = "select count(*) from " + form.getTableName() + " where instanceId in (" + listToString(instance) + ") and flowId='" + flowId + "'";
    Long total = Long.valueOf(this.flowFormDao.countBySql(sql).longValue());
    return total;
  }

  public List findBackFormList(int formId, String users, int currentPage) {
    OFormDefinition definition = getFormDefinition(formId);
    OFlowForm form = getFlowFormById(definition.getFormId().intValue());
    List<OFlowFormProporty> list = flowFormProportyList(definition.getFormId().intValue(), null);
    String sql = "select id";
    for (OFlowFormProporty p : list) {
      sql = sql + " ," + p.getColumnName();
    }
    sql = sql + " from " + form.getTableName() + " where reject='true' and instanceId is null and userId  in (" + users + ")";
    return this.flowFormDao.findByPageSql(sql, currentPage);
  }

  public Long countBackFormTotal(int formId, String users) {
    OFormDefinition definition = getFormDefinition(formId);
    OFlowForm form = getFlowFormById(definition.getFormId().intValue());
    String sql = "select count(*) from " + form.getTableName() + " where reject='true' and instanceId is null and userId in(" + users + ")";
    Long total = Long.valueOf(this.flowFormDao.countBySql(sql).longValue());
    return total;
  }

  public String getFormContent(int formId, int id) {
    OFlowForm form = getFlowFormById(formId);
    List<OFlowFormProporty> list = flowFormProportyList(formId, null);
    String sql = "select id";
    for (OFlowFormProporty p : list) {
      sql = sql + " ," + p.getColumnName();
    }
    sql = sql + " from " + form.getTableName() + " where id =" + id;
    List formList = this.flowFormDao.findBySql(sql);
    String json = "[";
    if ((formList != null) && (!formList.isEmpty())) {
      Object[] obj = (Object[])formList.get(0);
      json = json + "{'name':'ids','value':'" + obj[0].toString() + "'}";
      int m = 1;
      for (OFlowFormProporty p : list) {
        json = json + ",{'name':'" + p.getColumnName() + "','value':'" + isEmpty(obj[m]) + "'}";
        m++;
      }
    }
    json = json + "]";
    return json;
  }

  public String getInstanceId(int formId, int id) {
    OFlowForm form = getFlowFormById(formId);
    String sql = "select instanceId from " + form.getTableName() + " where id =" + id;
    List formList = this.flowFormDao.findBySql(sql);
    String instanceId = null;
    if ((formList != null) && (!formList.isEmpty()) && 
      (formList.get(0) != null)) {
      instanceId = ((BigDecimal)formList.get(0)).toString();
    }

    return instanceId;
  }

  public void updateRejectDraft(int formId, int id, OUser user)
  {
    OFlowForm form = getFlowFormById(formId);
    String sql = "update " + form.getTableName() + " set instanceId=null,reject='true',reject_s='被" + user.getName() + "退回' where id =" + id;
    this.flowFormDao.executeSql(sql);
  }

  public void updateRejectNode(int formId, int id, OUser user) {
    OFlowForm form = getFlowFormById(formId);
    String sql = "update " + form.getTableName() + " set reject='true',reject_s='被" + user.getName() + "退回' where id =" + id;
    this.flowFormDao.executeSql(sql);
  }

  public String getFlowCreatUser(int formId, int id) {
    OFlowForm form = getFlowFormById(formId);
    String sql = "select userId from " + form.getTableName() + " where id =" + id;
    List formList = this.flowFormDao.findBySql(sql);
    String instanceId = ((BigDecimal)formList.get(0)).toString();
    return instanceId;
  }

  private String listToString(List<OProcessinstance> list) {
    if ((list != null) && (!list.isEmpty())) {
      String id = "";
      for (int i = 0; i < list.size(); i++) {
        if (id == "")
          id = id + ((OProcessinstance)list.get(i)).getId();
        else {
          id = id + "," + ((OProcessinstance)list.get(i)).getId();
        }
      }
      return id;
    }
    return "";
  }

  private String isEmpty(Object value) {
    if (value == null) {
      return "";
    }
    return value.toString();
  }

  public Map<String, String> getLeaveById(String id)
  {
    Map map = new HashMap();
    String sql = "select jcoa_c481,jcoa_c429 from jcoa$t401 where id=" + id;
    List list = this.flowFormDao.findBySql(sql);
    if ((list != null) && (list.size() > 0)) {
      Object[] obj = (Object[])list.get(0);
      map.put("days", obj[0].toString());
      map.put("type", obj[1].toString());
    }
    return map;
  }
  public Map<String, String> getHolidayId(String id) {
    Map map = new HashMap();
    String sql = "select  jcoa_c501 from jcoa$t87 where id=" + id;
    List list = this.flowFormDao.findBySql(sql);
    if ((list != null) && (list.size() > 0)) {
      String days = (String)list.get(0);
      map.put("days", days);
    }
    return map;
  }
}